package com.nf.health.app.sweat.activity;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.util.RecyclerViewStateUtils;
import com.github.jdsjlzx.view.LoadingFooter;
import com.google.gson.Gson;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.adapter.SweatTrackListAdapter;
import com.nf.health.app.http.Act;
import com.nf.health.app.sweat.bean.SweatHistoryDataBean;
import com.nf.health.app.utils.ViewUtil;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by changpeng on 2016/11/04.
 * The only genius that is worth anything is the genius for hard work
 */
public class SweatAnalyzerHistoryTrackActivity extends BaseActivity {

    private static final String LOAD_MORE = "loadMore";
    private static final String REFRESH = "refresh";
    public static final String STATE_EDITOR = "编辑";
    public static final String STATE_COMPLET = "完成";
    private static final String FROM_SPORT = "sport";
    /**
     * 服务器端一共多少条数据
     */
    int totalCount;
    /**
     * 每一页展示多少条数据
     */
    int pageSize = 10;
    int pageNo = 1;
    String flag = "";
    /**
     * 已经获取到多少条数据了
     */
    private int mCurrentCounter = 0;
    private boolean isRefresh = false; //是否是下拉刷新

    @Bind(R.id.list)
    LRecyclerView mRecyclerView;
    @Bind(R.id.titlebar_right_tv)
    TextView titlebarRightTv;
    @Bind(R.id.v_time_line)
    View timeLine;

    private int delPosition = -1; //记录想要删除的汗液历史
    private LRecyclerViewAdapter mLRecyclerViewAdapter;
    private SweatTrackListAdapter mSweatTrackListAdapter;
    private List<SweatHistoryDataBean.DeviceDataBean> mDeviceDataBeens;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.layout_common_header);
        setContent(R.layout.activity_sweat_history_track);
        ButterKnife.bind(this);

        initView();
        initListener();
        initData("");

    }

    private void initView() {
        ViewUtil.setText(this, R.id.titlebar_title_tv, "历史记录");
        ViewUtil.setText(this, R.id.titlebar_right_tv, STATE_EDITOR);
        //titlebarRightTv.setVisibility(View.VISIBLE);
        String from = getIntent().getStringExtra(Constants.FROM);
        if(FROM_SPORT.equals(from)){
            titlebarRightTv.setVisibility(View.GONE);
        }else{
            titlebarRightTv.setVisibility(View.VISIBLE);
        }
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setPullRefreshEnabled(true);
        //设置样式
//        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
//        mRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
    }

    /**
     * @param flag 标记是刷新还是加载
     */
    private void initData(String flag) {
        this.flag = flag;
        provider.requestSweatData(pageNo + "", pageSize + "", Act.Flag.SWEAT_HISTORY_DATA);
    }

    private void initListener() {
        titlebarRightTv.setOnClickListener(this);
        mRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                RecyclerViewStateUtils.setFooterViewState(mRecyclerView, LoadingFooter.State.Normal);
                mSweatTrackListAdapter.clear();
                mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
                mCurrentCounter = 0;
                pageNo = 1;
                isRefresh = true;
                initData(REFRESH);
            }
        });

        mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
                if (state == LoadingFooter.State.Loading) {
                    return;
                }

                if (mCurrentCounter < totalCount) {
                    // loading more
                    pageNo++;
                    RecyclerViewStateUtils.setFooterViewState(SweatAnalyzerHistoryTrackActivity.this, mRecyclerView, pageSize, LoadingFooter.State.Loading, null);
                    initData(LOAD_MORE);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(SweatAnalyzerHistoryTrackActivity.this, mRecyclerView, pageSize, LoadingFooter.State.TheEnd, null);
                }
            }
        });
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {

        if (actionName.equals(Act.Flag.SWEAT_HISTORY_DATA)) {

            Gson gson = new Gson();
            SweatHistoryDataBean sweatHistoryDataBean = gson.fromJson(object + "", SweatHistoryDataBean.class);
            List<SweatHistoryDataBean.DeviceDataBean> newSweats = sweatHistoryDataBean.getDeviceData();
            if (mDeviceDataBeens == null) {
                mDeviceDataBeens = sweatHistoryDataBean.getDeviceData();
                totalCount = sweatHistoryDataBean.getTotalCount();
                if(mDeviceDataBeens == null || mDeviceDataBeens.size() == 0){
                    timeLine.setVisibility(View.GONE);
                }else{
                    timeLine.setVisibility(View.VISIBLE);
                }
                mSweatTrackListAdapter = new SweatTrackListAdapter(SweatAnalyzerHistoryTrackActivity.this, mDeviceDataBeens);

                mSweatTrackListAdapter.setOnItemClickLitener(new SweatTrackListAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        if(mDeviceDataBeens != null || mDeviceDataBeens.size() != 0) {
                            delPosition = position;
                            provider.delHistoryById(Constants.TYPE_SWEAT, mDeviceDataBeens.get(position).getId() + "", Constants.TYPE_SWEAT);
                        }
                    }
                });
                mLRecyclerViewAdapter = new LRecyclerViewAdapter(mSweatTrackListAdapter);
                mRecyclerView.setAdapter(mLRecyclerViewAdapter);
            } else {

                if (flag.equals(LOAD_MORE)) {
                    int currentSize = mSweatTrackListAdapter.getItemCount();
                    if (currentSize + sweatHistoryDataBean.getDeviceData().size() < totalCount) {
                        addItems(newSweats);
                    }
                    RecyclerViewStateUtils.setFooterViewState(mRecyclerView, LoadingFooter.State.Normal);
                }

                if (flag.equals(REFRESH)) {
                    if (isRefresh) {
                        mSweatTrackListAdapter.clear();
                        mSweatTrackListAdapter.addAll(newSweats);
                        mCurrentCounter = 0;
                        isRefresh = false;
                        mRecyclerView.refreshComplete();
                        RecyclerViewStateUtils.setFooterViewState(mRecyclerView, LoadingFooter.State.Normal);
                        notifyDataSetChanged();
                    }
                }
            }
        }

        //删除汗液历史
        if(actionName.equals(Constants.TYPE_SWEAT)){
            if(delPosition != -1) {
                mDeviceDataBeens.remove(delPosition);
                notifyDataSetChanged();
                showToast("删除成功");
            }
        }
    }

    @Override
    public void handleActionStart(String actionName, Object object) {
        if(actionName.equals(Constants.TYPE_SWEAT)){
            showLoading();
        }
        //第一次加载显示提示框，之后利用下拉刷新和上拉加载的提示即可
        if (mDeviceDataBeens == null) {
            showLoading();
        }
    }

    private void notifyDataSetChanged() {
        mLRecyclerViewAdapter.notifyDataSetChanged();
    }

    private void addItems(List<SweatHistoryDataBean.DeviceDataBean> list) {

        mSweatTrackListAdapter.addAll(list);
        mCurrentCounter += list.size();

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.titlebar_right_tv:
                String state = titlebarRightTv.getText().toString();
                if (mRecyclerView == null || mDeviceDataBeens == null) {
                    return;
                }
                if (state.equals(STATE_EDITOR)) {//编辑
                    //禁止下拉刷新
                    mRecyclerView.setPullRefreshEnabled(false);
                    for (SweatHistoryDataBean.DeviceDataBean deviceDataBeen : mDeviceDataBeens) {
                        deviceDataBeen.setEditState(true);
                    }
                    notifyDataSetChanged();
                    ViewUtil.setText(this, R.id.titlebar_right_tv, STATE_COMPLET);
                }
                if (state.equals(STATE_COMPLET)) {//完成
                    //启用下拉刷新
                    mRecyclerView.setPullRefreshEnabled(true);
                    for (SweatHistoryDataBean.DeviceDataBean deviceDataBeen : mDeviceDataBeens) {
                        deviceDataBeen.setEditState(false);
                    }
                    notifyDataSetChanged();
                    ViewUtil.setText(this, R.id.titlebar_right_tv, STATE_EDITOR);
                }
                break;
        }
    }
}
